//
//  PhysicsObject.m
//  CandyJump
//
//  Created by Bon Lam on 01/03/2011.
//  Copyright 2011 Peru Republic. All rights reserved.
//

#import "PhysicsObject.h"

#import "ccMacros.h"
#import "CCSprite.h"
#import "GCpShapeCache.h"

@implementation PhysicsObject

@synthesize physicsBodyName;

#pragma mark PhysicsObject - Basic
//---------------------------------------------------------------------------------------------------------------------
- (id)init
{
	self = [super init];
	if (self == nil)  {return self;}
	
	addBody = 0;
	
	return self;
}

//---------------------------------------------------------------------------------------------------------------------
- (void)dealloc
{
	[physicsBodyName release];
	
	//	Remove shapes
	for(cpShape *shape=physicsBody->shapesList; shape; shape=shape->next){
		cpSpaceRemoveShape(physicsSpace, shape);
		cpShapeFree(shape);
	}
	
	//	Remove Body
	if (physicsBody != nil)  {
		//  Body never added to space, no release required
		if (physicsSpace != nil && addBody)  {
			cpSpaceRemoveBody(physicsSpace, physicsBody);
		}
		cpBodyFree(physicsBody);
	}
	
	[super dealloc];
}

//---------------------------------------------------------------------------------------------------------------------
- (id)copyWithZone:(NSZone *)zone
{
	PhysicsObject *physicsObject = [super copyWithZone:zone];
	[physicsObject setPhysicsBodyName:self.physicsBodyName];
	physicsObject->addBody = addBody;
	return physicsObject;
}

#pragma mark PhysicsObject - Setters and Getters
//---------------------------------------------------------------------------------------------------------------------
- (cpBody*)physicsBody
{
	return physicsBody;
}

//---------------------------------------------------------------------------------------------------------------------
- (void)setPosition:(CGPoint)point
{
	physicsBody->p = cpv(point.x, point.y);
	[sprite setPosition:point];
}

#pragma mark PhysicsObject - Physics
//---------------------------------------------------------------------------------------------------------------------
- (void)setUpPhysics:(cpSpace *)space
{
	if (space == nil)  {return;}
	physicsSpace = space;
	
	physicsBody = [[GCpShapeCache sharedShapeCache] createBodyWithName:physicsBodyName inSpace:physicsSpace withData:self];
	
	physicsBody->p = cpv(sprite.position.x,sprite.position.y);
	
	physicsBody->v_limit = CANDY_JUMP_GLOBAL_PHYSICS_MAX_SPEED;
	physicsBody->w_limit = CANDY_JUMP_GLOBAL_PHYSICS_MAX_ANGULAR_SPEED;
	
	if (addBody) {
		cpSpaceAddBody(space, physicsBody);
	}
}

#pragma mark PhysicsObject - Update
//---------------------------------------------------------------------------------------------------------------------
- (void)update:(ccTime)dt
{
	CGPoint spritePosition = cpvadd(renderOffset, physicsBody->p);
	[sprite setPosition:spritePosition];
	[sprite setRotation:(float) CC_RADIANS_TO_DEGREES(-physicsBody->a)];
}

@end
